package com.gage.controller.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gage.controller.base.BaseController;
import com.gage.commons.result.PageInfo;
import com.gage.model.shiro.ShiroUser;
import com.gage.commons.utils.StringUtils;
import com.gage.model.CmsArticle;
import com.gage.model.CmsCatalog;
import com.gage.model.SysBaseDict;
import com.gage.service.ICmsArticleService;
import com.gage.service.ICmsCatalogService;
import com.gage.service.ISysDictService;

/**
 * <p>
 * 文章  前端控制器
 * </p>
 * @author kairu.lu
 * @since 2017-04-26
 */
@Controller
@RequestMapping("/app/article")
public class AppArticleController extends BaseController{
	@Autowired
	private ISysDictService sysDictService;
	@Autowired
	private ICmsCatalogService cmsCatalogService;
    /**
     * 注意：BaseController 中有xss过滤，会处理掉 ueditor 中的html
     * 
     * 所以你可以不继承它，或者注释掉BaseController中防止xss的代码
     * 
     * 毕竟管理平台几乎都是内网
     * 
     */
	@Autowired
	public ICmsArticleService cmsArticleService;
	
    @GetMapping("index")
    public String create() {
        return "app/article/index";
    }
    /**
	 * 加载树
	 * @author lkr
	 * @date:20170512
	 * @param request
	 * @param id
	 * @return
	 */
	@PostMapping("/catalog/tree")
    @ResponseBody
	public Object getCatalogTree(HttpServletRequest request,String id)
	{
		if (StringUtils.isBlank(id))
		{
			id = "daydayup_cms";
		}
		String catalogType="association";
		System.out.println(id);
		return cmsCatalogService.getCatalogTreeByParentIdAndType(id,catalogType);
	}
    /**
     * 文章管理列表
     *
     * @param userVo
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @PostMapping("/dataGrid")
    @ResponseBody
    public Object dataGrid(CmsArticle article,String catalogId,String username, Integer page, Integer rows, String sort, String order) {
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();

       if(StringUtils.isNotEmpty(catalogId)) {
            condition.put("catalogId",catalogId);
        }
       String associationId=this.getShiroUser().getAssociationId().toString();
       if (StringUtils.isNotEmpty(associationId)) {
           condition.put("associationId", associationId);
       }
       if(StringUtils.isNotEmpty(article.getTitle())) {
           condition.put("title",article.getTitle());
       }
       if(StringUtils.isNotEmpty(username)) {
           condition.put("username",username);
       }
        if (StringUtils.isNotEmpty(article.getInsertDate())) {
            condition.put("startTime", article.getInsertDate());
        }
        if (StringUtils.isNotEmpty(article.getInsertDate())) {
            condition.put("endTime", article.getInsertDate());
        }
        pageInfo.setCondition(condition);
        cmsArticleService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    /**
     * 添加文章信息页
      * @author lkr
      * @date:20170512
     * @return
     */
    @GetMapping("/add")
    public String addPage(Model model) {
    	String pid="articleType";
    	List<SysBaseDict> dictList=sysDictService.findDictByPid(pid);
    	model.addAttribute("dictList", dictList);
        return "app/article/edit";
    }
    /**
     * 编辑文章页
     *
     * @return
     */
    @GetMapping("/edit")
    public String editPage(String id,Model model) {
    	CmsArticle article=null;
    	if (StringUtils.isNotEmpty(id)) {
    		article=cmsArticleService.selectByPrimaryKey(Integer.parseInt(id));
    		List<String> catalogIdList=cmsArticleService.selectCatalogByArticleId(id);
    		String texts="";
        	String catalogIds="";
        	for (int i = 0; i < catalogIdList.size(); i++) {
        		catalogIds+=catalogIdList.get(i)+",";
        		CmsCatalog catalog=cmsCatalogService.loadCatalogByCatalogCode(catalogIdList.get(i));
        		if (StringUtils.isNotEmpty(catalog)) {
        			texts+=catalog.getCatalogName()+",";
				}
    		}
        	String pid="articleType";
        	List<SysBaseDict> dictList=sysDictService.findDictByPid(pid);
        	model.addAttribute("catalogIds", catalogIds);
        	model.addAttribute("dictList", dictList);
        	model.addAttribute("texts", texts);
        	model.addAttribute("article", article);
		}
        return "app/article/edit";
    }
    /**
     * @author lkr
     * @date:20170512
     * @param article
     * @param result
     * @return
     */
    @PostMapping("/save")
    @ResponseBody
	public Object save(@Valid CmsArticle article, BindingResult result){
		ShiroUser u = this.getShiroUser();
		Integer associationId=this.getAssociationId();
		if (StringUtils.isEmpty(article.getId())){
			article.setInsertDate(new Date());
			article.setInsertUid(Integer.parseInt(String.valueOf(u.getId())));
			article.setAssociationId(associationId);
			cmsArticleService.insertSelective(article);
		}else {
			article.setUpdateDate(new Date());
			article.setUpdateUid(Integer.parseInt(String.valueOf(u.getId())));
			cmsArticleService.updateByPrimaryKeySelective(article);
		}
		return resultJson("1","信息保存成功","");
	}
    /**
     * 删除
     * @author lkr
 	 * @date:20170512
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Object delete(String id) {
    	String[] ids = id.split(",");
    	List<String> list = new ArrayList<String>();
		for (int i = 0; i < ids.length; i++){
			list.add(ids[i].trim());
		}
		if (this.cmsArticleService.deleteByIds(list)>0)
		{
			return renderSuccess("成功删除"+ids.length+"条信息！");
		} else
		{
			return renderError("删除失败，删除操作出错！");
		}
    }
}
